<?php
declare (strict_types = 1);

namespace app\adminapi\service;
use app\adminapi\model\Admin\AdminSession;
use adminmatrix\admin\annotation\Inject;
use app\adminapi\cache\AdminTokenCache;
use think\facade\Config;
class AdminTokenService
{


    public  function setToken( string $adminId , $terminal = 1 , $multipointLogin =1){
        $time = time();
        $adminSession = (new AdminSession)->withSearch([
            'admin_id','terminal',
        ],[
            "admin_id"  =>  $adminId,
        ])->findOrEmpty();

        //获取token延长过期的时间
        $expireTime = $time + Config::get('adminmatrix.admin_token.expire_duration');

        $adminTokenCache = new AdminTokenCache();
        if($adminSession->isEmpty())
        {
            $adminSession = (new AdminSession)->create([
                'admin_id' => $adminId,
                'terminal' => $terminal,
                'token' => create_token($adminId),
                'expire_time' => $expireTime
            ]);
        }else{
            if ($adminSession->expire_time  < $time || $multipointLogin  == 0)
            {
                # 删除缓存
                $adminTokenCache->deleteAdminInfo($adminSession->token);
                $adminSession->token = create_token($adminId);
            }
            $adminSession->expire_time = $expireTime;
            $adminSession->update_time = $time;
            $adminSession->save();
        }

        return $adminTokenCache->setAdminInfo($adminSession->token);
    }

    public static function expireToken($token)
    {
        $adminSession = AdminSession::where('token', '=', $token)
            ->with('admin')
            ->findOrEmpty();

        if ($adminSession->isEmpty()) {
            return false;
        }

        //当支持多处登录的时候，服务端不注销
        if ($adminSession->admin->multipoint_login === 1) {
            return false;
        }

        $time = time();
        $adminSession->expire_time = $time;
        $adminSession->update_time = $time;
        $adminSession->save();

        return (new AdminTokenCache())->deleteAdminInfo($token);
    }

}
